<template>
  <div class="category-list-container">
    <div class="header-actions">
      <h2>分类管理</h2>
      <el-button type="primary" @click="showAddDialog = true">添加分类</el-button>
    </div>

    <el-table :data="categories" v-loading="loading" border stripe>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="分类名称"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog v-model="showAddDialog" :title="dialogTitle">
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryFormRules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { categoryApi } from '@/api/categoryApi'
import { categoryFormRules } from '@/utils/formRules'

const categories = ref([])
const loading = ref(false)
const showAddDialog = ref(false)
const categoryFormRef = ref(null)
const dialogTitle = ref('添加分类')
const currentCategoryId = ref(null)

// 添加分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const categoryForm = ref({
  name: ''
})

// 更新获取分类列表方法，支持分页
const getCategories = async () => {
  loading.value = true
  try {
    const response = await categoryApi.getCategories(currentPage.value, pageSize.value)
    categories.value = response.data.content
    total.value = response.data.totalElements // 假设后端返回total字段表示总条数
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 添加分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置为第一页
  getCategories()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getCategories()
}

// 添加/编辑分类提交
const handleSubmit = async () => {
  if (!categoryFormRef.value) return
  try {
    await categoryFormRef.value.validate()
    if (currentCategoryId.value) {
      // 更新分类
      await categoryApi.updateCategory(currentCategoryId.value, categoryForm.value)
      ElMessage.success('分类更新成功')
    } else {
      // 创建分类
      await categoryApi.createCategory(categoryForm.value)
      ElMessage.success('分类创建成功')
    }
    showAddDialog.value = false
    getCategories()
    resetForm()
  } catch (error) {
    console.error('提交分类失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  currentCategoryId.value = row.id
  categoryForm.value = { ...row }
  showAddDialog.value = true
}

// 删除分类
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await categoryApi.deleteCategory(id)
    ElMessage.success('分类删除成功')
    getCategories()
  } catch (error) {
    console.error('删除分类失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 重置表单
const resetForm = () => {
  categoryForm.value = { name: '' }
  currentCategoryId.value = null
  dialogTitle.value = '添加分类'
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
}

onMounted(() => {
  getCategories()
})
</script>

// 添加分页样式
<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>